package tr.edu.yildiz.ce.dap.appagent.process;

import tr.edu.yildiz.ce.dap.appagent.command.deployment.agent.RegisterCommand;
import tr.edu.yildiz.ce.dap.appagent.command.deployment.agent.RetrieveCommand;
import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.CommandConstants;
import tr.edu.yildiz.ce.dap.appagent.conf.DynamicProxyConfiguration;
import tr.edu.yildiz.ce.dap.appagent.exception.BasicAgentException;
import tr.edu.yildiz.ce.dap.appagent.manager.AgentProcessManager;
import tr.edu.yildiz.ce.dap.appagent.model.App;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.service.MessageConverter;
import tr.edu.yildiz.ce.dap.appagent.util.AgentProperties;

public class RegistrationProcess extends MulticastReceiverProcess{

	String multicastAddress;
	Integer port;
	
	public RegistrationProcess(AgentProcessManager processManager, String multicastAddress,Integer port) {
		super(processManager,multicastAddress,port);
	}
	
	@Override
	protected void onMulticastPacketReceived(String message) throws BasicAgentException {
		 DapMessage mCastMessage = null;
			try {
				mCastMessage = MessageConverter.convertToObject(message);
				initializeProxyConfiguration(mCastMessage);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			DapMessage registerMessage = prepareRegisterMessage(mCastMessage);
			
			RegisterCommand registerCommand = new RegisterCommand(this);
			DapMessage registrationResponse = registerCommand.execute(registerMessage);
			if (registrationResponse.getAppList() != null){
				for (App app : registrationResponse.getAppList().getApp()) {
					RetrieveCommand retrieveCommand = new RetrieveCommand(this, app.getName(), app.getVersion());
					retrieveCommand.execute(new DapMessage());
				}
			}
		
	}

	
	private DapMessage prepareRegisterMessage(DapMessage mCastMessage){
		DapMessage registerMessage = new DapMessage();
		registerMessage.setCommand(CommandConstants.REGISTER);
		registerMessage.setAgentName(AgentProperties.getInstance().getName());
		registerMessage. setAgentListeningPort(AgentProperties.getInstance().getListeningPort());
		return registerMessage;
		
	}
	
	private void initializeProxyConfiguration(DapMessage mCastMessage){
		DynamicProxyConfiguration.getInstance().setProxyAddress(mCastMessage.getProxyAddress());
		DynamicProxyConfiguration.getInstance().setPort(mCastMessage.getProxyPort().intValue());
	}

	@Override
	protected void onMulticastConnectionFailed() throws BasicAgentException {
		
	}
	

}
